package com.rulin.huanxin_demo.utlis.im.helper;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.exceptions.HyphenateException;
import com.rulin.huanxin_demo.utlis.FCCallBack;
import com.rulin.huanxin_demo.utlis.FCError;
import com.rulin.huanxin_demo.utlis.ThreadManager;


import java.util.Iterator;
import java.util.List;

/**
 * Created by LWK
 * 环信sdk帮助类
 * [除了聊天相关的所有方法都在这里]
 * 2016/8/4
 */
public class HxSdkHelper {
    private static final String TAG = "HxSdkHelper";

    private HxSdkHelper() {
    }

    private static final class HxSdkHelperHolder {
        public static HxSdkHelper instance = new HxSdkHelper();
    }

    public static HxSdkHelper getInstance() {
        return HxSdkHelperHolder.instance;
    }

    private Context mAppContext;
    private boolean mIsSdkInited;
    private boolean mHasAsyncUserList;

    /**
     * 初始化环信sdk
     * 放在Application的onCreate()
     */
    public void initSdkOptions(Context context) {
        if (mIsSdkInited)
            return;

        mAppContext = context.getApplicationContext();

        // 获取当前进程 id 并取得进程名
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        /**
         * 如果app启用了远程的service，此application:onCreate会被调用2次
         * 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
         * 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process name就立即返回
         */
        if (processAppName == null || !processAppName.equalsIgnoreCase(mAppContext.getPackageName())) {
            // 则此application的onCreate 是被service 调用的，直接返回
            return;
        }

        /**
         * SDK初始化的一些配置
         * 关于 EMOptions 可以参考官方的 API 文档
         * http://www.easemob.com/apidoc/android/chat3.0/classcom_1_1hyphenate_1_1chat_1_1_e_m_options.html
         */
        EMOptions options = new EMOptions();
        // 设置Appkey，如果配置文件已经配置，这里可以不用设置
        // options.setAppKey("guaju");
        // 设置自动登录
        options.setAutoLogin(true);
        // 设置是否需要发送已读回执
        options.setRequireAck(true);
        // 设置是否需要发送回执，TODO 这个暂时有bug，上层收不到发送回执
        options.setRequireDeliveryAck(true);
        // 设置是否需要服务器收到消息确认
        options.setRequireServerAck(true);
        // 收到好友申请是否自动同意，如果是自动同意就不会收到好友请求的回调，因为sdk会自动处理，默认为true
        options.setAcceptInvitationAlways(false);
        // 设置是否自动接收加群邀请，如果设置了当收到群邀请会自动同意加入
        options.setAutoAcceptGroupInvitation(false);
        // 设置（主动或被动）退出群组时，是否删除群聊聊天记录
        options.setDeleteMessagesAsExitGroup(false);
        // 设置是否允许聊天室的Owner 离开并删除聊天室的会话
        options.allowChatroomOwnerLeave(true);

        // 设置google GCM推送id，国内可以不用设置
        // options.setGCMNumber(MLConstants.ML_GCM_NUMBER);
        // 设置集成小米推送的appid和appkey
        // options.setMipushConfig(MLConstants.ML_MI_APP_ID, MLConstants.ML_MI_APP_KEY);

        // 调用初始化方法初始化sdk
        EMClient.getInstance().init(mAppContext, options);
        // 设置开启debug模式
        EMClient.getInstance().setDebugMode(true);
        // 设置初始化已经完成
        mIsSdkInited = true;


        Log.i(TAG, "初始化环信.....");
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) mAppContext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = mAppContext.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }

    /**
     * 注册方法
     *
     * @param phone    手机号
     * @param pwd      密码
     * @param callBack 回调【注意回调会在子线程中】
     */
    public void regist(final String phone, final String pwd, final FCCallBack callBack) {
        ThreadManager.getInstance().addNewRunnable(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(phone, pwd);
                    if (callBack != null)
                        callBack.onSuccess(null);
                } catch (HyphenateException e) {

                    Log.e(TAG, "HxSdk regist from server fail : hxErrCode = " + e.getErrorCode() + " , msg = " + e.getMessage());
                    if (callBack != null)
                        callBack.onFail(FCError.REGIST_FAIL, FCError.getErrorMsgIdFromCode(e.getErrorCode()));
                }
            }
        });
    }

    /**
     * 手动登录环信的方法
     *
     * @param phone    手机号
     * @param pwd      密码
     * @param callBack 回调
     */
    public void login(final String phone, final String pwd, final int flag, final FCCallBack callBack) {
        EMClient.getInstance().login(phone, pwd, new EMCallBack() {
            @Override
            public void onSuccess() {

                Log.i(TAG, "HxSdk login from server success");
                // 加载所有会话到内存
                loadHxLocalData(flag);
                if (callBack != null)
                    callBack.onSuccess(null);
            }

            @Override
            public void onError(int code, String msg) {

                Log.e("HxSdkHelper", "HxSdk login fail : hxErrCode = " + code + " , msg = " + msg);
                if (callBack != null)
                    callBack.onFail(FCError.LOGIN_FAIL, FCError.getErrorMsgIdFromCode(code));
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

    /**
     * 判断是否能自动登录
     */
    public boolean canAutoLogin() {
        return EMClient.getInstance().isLoggedInBefore();
    }

    /**
     * 加载环信本地数据
     */
    public void loadHxLocalData(int flag) {

        switch (flag) {

            case 1:
                EMClient.getInstance().groupManager().loadAllGroups();

                Log.i("HxSdkHelper", "HxSdk load all groups success");

                break;
            case 2:
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.i("HxSdkHelper", "HxSdk load all Conversations success");
                break;
            default:
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.i("HxSdkHelper", "HxSdk load all groups  Conversations success");
                break;
        }

    }

    /**
     * 退出环信登录
     *
     * @param callBack 回调
     */
    public void logout(final FCCallBack callBack) {
        if (!EMClient.getInstance().isLoggedInBefore()) {
            if (callBack != null)
                callBack.onSuccess(null);
            return;
        }
        EMClient.getInstance().logout(true, new EMCallBack() {
            @Override
            public void onSuccess() {
                resetFlags();
//                DbOpenHelper.getInstance(FCApplication.getInstance()).close();
                if (callBack != null)
                    callBack.onSuccess(null);
            }

            @Override
            public void onError(int i, String s) {
                resetFlags();
//                DbOpenHelper.getInstance(FCApplication.getInstance()).close();
                if (callBack != null)
                    callBack.onFail(FCError.LOGOUT_FAIL, FCError.getErrorMsgIdFromCode(i));
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    //将某些标记位还原
    private void resetFlags() {
        mHasAsyncUserList = false;
    }

    /**
     * 获取当前登录的账号
     *
     * @return 当前登录账号
     */
    public String getCurLoginUser() {
        return EMClient.getInstance().getCurrentUser();
    }

    /**
     * 添加连接监听
     *
     * @param listener 环信连接监听
     */
    public void addConnectListener(EMConnectionListener listener) {
        if (listener != null)
            EMClient.getInstance().addConnectionListener(listener);
    }

    /**
     * 移除连接监听
     *
     * @param listener 环信连接监听
     */
    public void removeConnectListener(EMConnectionListener listener) {
        if (listener != null)
            EMClient.getInstance().removeConnectionListener(listener);
    }


}
